<?php
/**
 * @version		$Id:  $
 * @package		Success Framework Mobile
 * @subpackage	Helper
 * @copyright	Copyright (C) 2007 - 2010 Success company - VietNam. All rights reserved.
 */
 
class sscls_Helper
{
    function connectdb()
    {
        
       return $this->connect_db();
    }
    
    function get($classname='Factory')
    {
        return $class=new $classname;
    }
    //save to database by id
    function save($data,$tablename)
    {
        global $db;
    	if((int)$data['id']!=0)
    	{			
    			foreach($data as $key=>$fied)
    			{
    				if($key!='id')
    				{
    						$set[]=$key.'=\''.$fied.'\'';
    				}
    			}
    		$sets=(count($set)?' update '.$tablename.' set  '.implode(',',$set): '');
    		$where=' where  id = '.$data['id'];
    		$query=$sets.$where;
            
    	}
    	else
    	{	//var_dump($data);
    		foreach((array)$data as $key=>$fied)
    			{
    				if($key!='id')
    				{
    						$field[]=$key;
    						$value[]=$fied;
    				}
    			}
    		$query=(count($field)?' INSERT INTO '.$tablename.' ('.implode(',',$field).' ) VALUES (\''.implode('\',\'',$value).'\')':'');
            //echo $query; 
    	}
        //echo $query;die;
        
    		if($db->query($query))
    			return true;
    		else
    			return false;
    }
    
    
    ///delete record by id 
    function deletebyid($id_array,$tablename)
    {
        global $db;
    	$query=' delete from  '.$tablename.' where id in('.$id_array.')';
     //echo $query;die;
    		if($db->query($query))
    			return true;
    		else
    			return false;
    }
    
    //load record list 
    function loadlist($tablename,$fields='',$where='')
    {
    	global $db;
        if($fields=='')
        $fields='*';
        $query='select '.$fields.' from '.$tablename.' '.$where;
        return $db->loadObjectList($query);
        
    }
    function loadbyid($tablename,$id,$fields='')
    {
        global $db;
        if($fields=='')
        $fields='*';
        $query='select '.$fields.' from '.$tablename.' where id='.$id;
        return $db->loadObject($query); //$db->query($query,true);
    }
    
    function getList($table,$where='',$limit=0,$option='',$orderby='id')
    {
        global $db,$main;
        $limitstart_=Request::getRequest('limitstart');
       
        $firts=Request::getRequest('firts');
        $session=$main->getSession();
        if((int)$firts==1)
        {
         $session->set('limitstart.'.$option,$limitstart_);  
        }
        $limitstart=(int)$session->get('limitstart.'.$option);
        if($limitstart!=0)
        {
            $limitstart1=$limitstart+1;
        }
        $total=count($db->loadObjectList('select * from '.$table.' '.$where));
        $object=$main->get('object');
        $t=(int)$limit+(int)$limitstart;
        if($limit!=0)
        {
            $query='SELECT * FROM ( SELECT row_number() OVER (ORDER BY '.$orderby.') AS rownum, * FROM   '.$table.' '.$where.') AS A WHERE A.rownum BETWEEN ('.(int)$limitstart1.') AND ('.$t.')';
        }
        //echo $query;
        $rows=$db->loadObjectList($query);
        $object->add('value',$rows);
        $object->add('pagination',$main->pagination($limit,$limitstart,$total,$option));
         return $object;
    }
    
    function pagination($limit,$limitstart,$total,$option)
    {
        global $main;
        $object=$main->get('object');
        $object->add('total',(int)$total);
        $object->add('limit',(int)$limit);
        $object->add('limitstart',(int)$limitstart);
        $object->add('option',$option);
        $object->add('pagetotal',gettype($total/$limit)=='integer'?$total/$limit:(int)($total/$limit)+1);
        $object->add('pagecurrent',(int)$limitstart/$limit+1);
        return $object;        
    }
    
    function sendmailsmtp1($to,$toname='',$from='',$fromname='',$subject,$message)
    {
      
        $object=$this->get('object');
        $msg=Resources::_('Lỗi gửi mail');
        $object->add('msg',$msg);
        $object->add('suc',false);
        // To send HTML mail, the Content-type header must be set
        $headers  = 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
        
        // Additional headers
        $headers .= 'To: '.$to. "\r\n";
        $headers .= 'From: '.$from. "\r\n";
//        echo $to.'<br/>'.$from.'<br/>'.$subject.'<br/>'.$message;
//        die;
        // Mail it
        if(@mail($to, $subject, $message, $headers))
        {
             $object->suc=true;
            return $object;
        }
        return $object;
    }
    
    function sendmailsmtp2($to,$toname='',$from='',$fromname='',$subject,$body)
    {
        require_once "Mail/Mail.php";
        
        $object=$this->get('object');
        $msg=Resources::_('SENDMAIL');
        $object->add('msg',$msg);
        $object->add('suc',true);
        
        $conf=$this->getConfig();
        
        if($from=='')
        {
            $from =$conf['usernamemail'];
        }
        
        if($fromname=='')
        {
            $fromname=trim($conf['webtitle']);
        }
        $from1 = $fromname.'< '.$from.' >';
        $to = $toname.'< '.$to.' >';
        $host = trim($conf['hostmail']);
        $username = trim($conf['usernamemail']);
        $password = trim($conf['passwordemail']);
        $headers = array ('MIME-Version'=>'1.0 \r\n',
            'Content-type' =>'text/html; charset=utf-8 \r\n',
            'From' => $from1,
            'To' => $to,
            'Subject' => $subject);
        $smtp = Mail::factory('smtp',
          array ('host' => $host,
            'auth' => true,
            'username' => $username,
            'password' => $password));
        $mail = $smtp->send($to, $headers, $body);
        if (PEAR::isError($mail)) {
           // $msg=Resources::_('SENDMAIL');
            $object->msg= $mail->getMessage();
            $object->suc=false;
            return $object;
         } else {
            return $object;
         }
    }
    
    function sendmailsmtp($to,$toname='',$from='',$fromname='',$subject,$body)
    {
       // require_once "Mail/Mail.php";
        
        $object=$this->get('object');
        $msg=Resources::_('Lỗi gửi mail');
        $object->add('msg',$msg);
        $object->add('suc',false);
        
        $data['email']=$to;
        $data['subject']=$subject;
        $data['emailcontent ']=$body;
        if($this->save($data,'mailqueue'))
        {
            
            $object->suc=true;
            return $object;
        }
        return $object;
    }
    function valueexists($tablename,$field,$value)
    {
        global $db;
        $query='select '.$field.' from '.$tablename.' where '.$field.'="'.$value.'"';
        if($db->query($query,true))
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    
    function getSession()
    {
        global $main;
		
		//Cu~
        // File::import('includes/session.php');
		
		//Moi, Phu sua lai thanh duong dan dong va tuyet doi
		File::import(dirname(__FILE__) . '/session.php');
        return $main->get('session');
        
    }
    
    function getclass($com='',$classname='')
    {
        return Component::getClass($com,$classname);
    }
    
    function getConfig()
    {
        global $db;
        $config=$db->loadObjectList('select * from config');
        $conf=array();
        foreach($config as $cf)
        {
            $conf[$cf->name]=$cf->value;
        }
        return $conf;
    }
    function checkcaptcha($name='',$value='')
    {
        @session_start();
        //echo $_SESSION['captchass'.$name].'</br>'.$value;die;
        if($_SESSION['captchass'.$name]==$value)
        {
            return true;
        }
        
        return false;
        
    }
    
     //Kiem tra tinh hop le cua email
    function checkemailvalid($mailStr)
    {
        $pattern = '/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/';
        if(preg_match($pattern, $mailStr)==0) {
            return false;
        }
        else
            return true;
    }
    
    function getRString($stringlength = 7)
    {
        $acceptedChars = 'ABCDEFGHIJKLMNPQRSTUVWXYZ123456789';
        $max = strlen($acceptedChars)-1;
        $password = NULL;
        for($i=0; $i < $stringlength; $i++) {
        	$cnum[$i] = $acceptedChars{mt_rand(0, $max)};
        	$password .= $cnum[$i];
        }
        return $password;
    }
}
?>
